# encoding:utf-8
import glob
import os
import pprint
import time

import requests
import base64

from tqdm import tqdm

'''
通用物体和场景识别
'''

def get_access_token(id,secret):
    get_access_token_url='https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id='+id+'&client_secret='+secret
    response=requests.get(get_access_token_url)
    content=response.json()
    access_token=content['access_token']
    return access_token


def Animation(img_file,access_token, list_main_element):
    request_url='https://aip.baidubce.com/rest/2.0/image-classify/v2/advanced_general'
    f=open(img_file,'rb')
    image=base64.b64encode(f.read())
    params = {"image":image}
    request_url = request_url + "?access_token=" + access_token
    headers = {'content-type': 'application/x-www-form-urlencoded'}
    response = requests.post(request_url, data=params, headers=headers)
    if response:
        # print(response.json())
        try:
            list_result = response.json()['result']
            list_main = list_result[0]
            print(list_main)
            list_main_element.append(list_main)
        except:
            print('识别失败')
    return response.json()



def get_image_names(folder_path):
    image_extensions = ['.jpg', '.jpeg', '.png', '.gif']  # 定义常见的图片文件扩展名

    # 构建要搜索的文件路径模式
    search_pattern = os.path.join(folder_path, '*')

    # 使用 glob 模块根据文件路径模式获取所有文件的列表
    all_files = glob.glob(search_pattern)

    # 筛选出图片文件并提取文件名（包括后缀名）
    image_names = [os.path.basename(file) for file in all_files if
                   os.path.splitext(file)[1].lower() in image_extensions]

    return image_names

    # 指定要搜索的文件夹路径

def ai_start(file_name):
    id = '7VOxFRA4hN09OLZRyNLzcas1'
    secret = 'GHs9ynuOAWAWomSUFUUoLgv4sMU5skqC'
    # 主要元素列表
    list_main_element = []

    access_token = get_access_token(id, secret)
    result = Animation(file_name, access_token, list_main_element)
    return result

if __name__ == '__main__':

    id = '7VOxFRA4hN09OLZRyNLzcas1'
    secret = 'GHs9ynuOAWAWomSUFUUoLgv4sMU5skqC'
    # 主要元素列表
    list_main_element = []
    folder_path = 'E:/program/flask_vilipixiv/vilipixiv/static/img_top20'
    images = get_image_names(folder_path)

    # 调用函数获取图片文件的名称列表
    image_names = get_image_names(folder_path)
    for i in range(len(image_names)):
        # 图片地址
        img_file = f'E:/program/flask_vilipixiv/vilipixiv/static/img_top20/{image_names[i]}'

        access_token = get_access_token(id, secret)
        Animation(img_file, access_token, list_main_element)
        time.sleep(0.2)
    print(list_main_element)